package com.wf.service.articleServiceImpl;

import com.alibaba.fastjson.JSON;
import com.wf.dao.pojo.SysUser;
import com.wf.service.LoginService;
import com.wf.service.SysUserService;
import com.wf.utils.JWTUtils;
import com.wf.vo.ErrorCode;
import com.wf.vo.Result;
import com.wf.vo.params.LoginParam;
import com.wf.vo.params.RegisterParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.concurrent.TimeUnit;

@Service
@Transactional
@Slf4j
public class LoginServiceImpl implements LoginService {

    private static final String slat = "hide***";
    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public Result login(LoginParam loginParam) {
        String account = loginParam.getAccount();
        String password = loginParam.getPassword();
        //如果传入的参数为空，直接返回异常
        if (StringUtils.isBlank(account) || StringUtils.isBlank(password)){
            return Result.fail(ErrorCode.PARAMS_ERROR.getCode(),ErrorCode.PARAMS_ERROR.getMsg());
        }
        //处理密码
        String pwd = DigestUtils.md5Hex(password + slat);
        //根据处理后密码登录用户
        SysUser sysUser = sysUserService.findUser(account,pwd);
        //找不到用户就登录失败
        if (sysUser == null){
            return Result.fail(ErrorCode.ACCOUNT_PWD_NOT_EXIST.getCode(),ErrorCode.ACCOUNT_PWD_NOT_EXIST.getMsg());
        }
        //找到用户，登录成功，使用JWT生成token，返回token,和存入redis中
        String token = JWTUtils.createToken(sysUser.getId());
        redisTemplate.opsForValue().set("TOKEN_"+token, JSON.toJSONString(sysUser),1, TimeUnit.DAYS);
        log.info("=================成功写入token===========================");
        log.info(token);
        return Result.success(token);
    }

    @Override
    public Result logout(String token) {
        redisTemplate.delete("TOKEN_"+token);
        return Result.success(null);
    }

    @Override
    public Result register(RegisterParam registerParam) {
        String account = registerParam.getAccount();
        String password = registerParam.getPassword();
        String nickname = registerParam.getNickname();
        if (StringUtils.isBlank(account)
                || StringUtils.isBlank(password)
                || StringUtils.isBlank(nickname)
        ){
            log.info("用户名为空");
            return Result.fail(ErrorCode.PARAMS_ERROR.getCode(),ErrorCode.PARAMS_ERROR.getMsg());
        }
        //查找是否账号重复
        SysUser sysUser = sysUserService.findUserByACcount(account);
        if(sysUser != null){
            log.info("账号已存在，创建失败");
            return Result.fail(ErrorCode.ACCOUNT_EXIST.getCode(),ErrorCode.ACCOUNT_EXIST.getMsg());
        }
        log.info("账号不存在，可以创建新账号");
        //账号未被使用，可以注册
        sysUser = new SysUser();
        sysUser.setNickname(nickname);
        sysUser.setAccount(account);
        sysUser.setPassword(DigestUtils.md5Hex(password+slat));
        sysUser.setCreateDate(System.currentTimeMillis());
        sysUser.setLastLogin(System.currentTimeMillis());
        sysUser.setAvatar("/static/img/logo.b3a48c0.png");
        sysUser.setAdmin(1); //1 为true
        sysUser.setDeleted(0); // 0 为false
        sysUser.setSalt("");
        sysUser.setStatus("");
        sysUser.setEmail("");
        log.info("存入用户："+sysUser.toString());
        sysUserService.save(sysUser);

        //生成登录 token 并存入 redis
        String token = JWTUtils.createToken(sysUser.getId());
        String key = "TOKEN_"+token;
        String value = JSON.toJSONString(sysUser);
        log.info("将 token 存入 redis 中-----"+key+":"+value);
        redisTemplate.opsForValue().set(key,value ,1, TimeUnit.DAYS);
        return Result.success(token);
    }

    @Override
    public SysUser checkToken(String token) {
        String key = "TOKEN_" + token;
        log.info(key);
        String sysUserJson = redisTemplate.opsForValue().get(key);
        log.info("从redis中查到登录信息:"+sysUserJson);
        return JSON.parseObject(sysUserJson, SysUser.class);
    }


}
